package com.clt.web.interceptor;

import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.clt.web.common.Oauth;
import com.clt.web.common.WeiXinPropertiesUtil;
import com.clt.web.utils.ServletUtils;

/**
 * 登录拦截器 用来授权
 * 
 * @author wenjian
 * 
 */
public class ActionInterceptor extends HandlerInterceptorAdapter {

	private final Logger logger = LoggerFactory.getLogger(getClass());
	public final static String X_R = "X-Requested-With";
	public final static String X_R_VALUE = "XMLHttpRequest";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		String uri = request.getRequestURI();
		logger.info("用户访问 url:{}", uri);
		HttpSession session = request.getSession();
		// 配置文件中开启了微信授权才会进行过滤器逻辑
		if (WeiXinPropertiesUtil.isOpenOauth() && uri.contains("/weixin/")) {
			// 拦截器逻辑开始
			String openid = (String) session.getAttribute("myOpenid");
			Cookie[] cookies = null;
			// session里没有openId
			if (null == openid||"".equals(openid)) {
				logger.info("session里面没有openId,查看cookie里的openId");
				// 获取cookie
				cookies = request.getCookies();
				if (null != cookies) {
					for (int i = 0; i < cookies.length; i++) {
						if (cookies[i].getName().equals("myOpenid")) {
							openid = cookies[i].getValue();
							logger.info("cookie里的openId有值={}", openid);
							break;
						}
					}
				}
			}
			// 如果已经有用户openid了，就直接跳转,无需授权,无openid操作如下
			if (null == openid||"".equals(openid)) {
				// 微信用户授权接口所需
				String code = request.getParameter("code");
				if (code != null) {
					logger.info("用户请求的code 有值{}", code);
					// 看是否调用了授权接口，调用了的话在这里取得用户信息
					JSONObject jsonObject = JSONObject.fromObject(Oauth.getToken(code));
					openid = jsonObject.getString("openid");
					// 保存session
					session.setAttribute("myOpenid", openid);
					// 保存cookie
					Cookie cookie = new Cookie("myOpenid", openid);
					response.addCookie(cookie);
					logger.info("得到myOpenid is {}", openid);
					return super.preHandle(request, response, handler);
				}
				else {
					logger.info("用户请求的 code 没值,表示需要授权");
					// 没有调用授权接口，那么就调用它
					// 获得现在的网址
					String currenturl = request.getRequestURL()
							+ (request.getQueryString() == null ? "" : ("?" + request.getQueryString()));
					// 构造授权接口地址
					String redirectUrl = Oauth.getCode(URLEncoder.encode(currenturl, "utf-8"), true);
					// 直接跳转到目标url
					ServletUtils.redirectToUrl(request, response, redirectUrl);
				}
			}else{
				// 保存session
				session.setAttribute("myOpenid", openid);
				// 保存cookie
				Cookie cookie = new Cookie("myOpenid", openid);
				response.addCookie(cookie);
			}
		}
		return super.preHandle(request, response, handler);
	}
}
